package com.hjy.study.studyspringcloudpublic.configuration;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * RESTful微服务没有配置跨源CORS设置,在此设置
 * Created by hjy on 2018/6/13.
 */
@Configuration
public class SecurityCorsConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin(CorsConfiguration.ALL);//1、允许任何域名使用
        config.addAllowedHeader(CorsConfiguration.ALL);// 2、允许任何头
        config.addAllowedMethod(CorsConfiguration.ALL);// 3、允许任何方法（post、get等）PUT,DELETE,POST,GET"

        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }

}